package soulkun.library.custom.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import androidx.databinding.BindingAdapter
import androidx.databinding.ObservableBoolean
import soulkun.library.utils.*

class RectangleBorderImageView : androidx.appcompat.widget.AppCompatImageView {

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var borderWidth = 0
    private var borderColor = Color.BLACK
    private var dataBindingBorderWidth: Int? = null
    private var dataBindingBorderColor: Int? = null

    companion object {
        //单向绑定
        @BindingAdapter("app:rectangleBorderWidth")
        @JvmStatic
        fun setRectangleBorderWidth(view: RectangleBorderImageView, params: Int) {
            if (view.dataBindingBorderWidth != params) {
                view.dataBindingBorderWidth = params
                view.invalidate()
            }
        }

        //单向绑定
        @BindingAdapter("app:rectangleBorderColor")
        @JvmStatic
        fun setRectangleBorderColor(view: RectangleBorderImageView, params: Int) {
            if (view.dataBindingBorderColor != params) {
                view.dataBindingBorderColor = params
                view.invalidate()
            }
        }
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectangleBorderImageView)
        borderWidth =
            typedArray.getDimensionPixelSize(
                R.styleable.RectangleBorderImageView_rectangleBorderWidth,
                0
            )
        borderColor = typedArray.getColor(
            R.styleable.RectangleBorderImageView_rectangleBorderColor,
            Color.BLACK
        )
        typedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rect = canvas.clipBounds
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = (dataBindingBorderWidth ?: borderWidth).toFloat()
        mPaint.color = dataBindingBorderColor ?: borderColor
        canvas.drawRect(rect, mPaint)
    }

}